import { defineStore } from 'pinia';
import SiderMenu from '../data/model/menu/sider-menu';
import TopMenu from '../data/model/menu/top-menu';
import { isString, getCurrentAccount, split, isEmpty, pick } from '@jecloud/utils';
/**
 * 菜单store
 */
export const useMenuStore = defineStore({
  id: 'menu-store',
  state: () => ({
    siderMenus: new Map(), // 左侧菜单
    topMenus: new Map(), //顶部菜单
    searchMenus: [], // 用于查询的菜单
    starMenus: [], // 收藏菜单
    historyMenus: [], // 历史菜单
    activeSiderMenu: null, // 激活左侧菜单
    activeTopMenu: null, // 激活顶部菜单
    activeSiderTab: 'tree', // 激活左侧菜单面板
    openMenus: [], // 打开的菜单
    topMenuAlign: 'center', // 顶部菜单位置
    topMenuLogo: null, // 顶部菜单logo
    init: false, // 菜单初始化
    openAction: '', // 打开菜单操作
    prevHistoryMenuEnable: false, // 启用记录功能使用状态
    prevHistoryMenus: [], // 上次操作历史菜单
  }),
  getters: {
    /**
     * 顶部菜单对应的左侧ROOT菜单
     * @param {*} state
     * @returns
     */
    activeSiderRoot(state) {
      // const topMenu = state.topMenus.get(state.activeTopMenu);
      const topMenu = state.siderMenus.get(state.activeTopMenu);
      const siderRoot = state.getMenuById(topMenu?.id);
      return siderRoot?.id;
    },
    /**
     * 收藏菜单完整数据
     * @param {*} state
     * @returns
     */
    computeStarMenus(state) {
      return state.starMenus.map((id) => this.getMenuById(id));
    },
    /**
     * 历史菜单完整数据
     * @param {*} state
     * @returns
     */
    computeHistoryMenus(state) {
      return state.historyMenus.map((id) => this.getMenuById(id));
    },
    /**
     * 打开菜单完整数据
     * @param {*} state
     * @returns
     */
    computeOpenMenus(state) {
      return state.openMenus.map((id) => this.getMenuById(id));
    },
    /**
     * 上次操作菜单本地缓存key
     * @returns
     */
    menuPrevHistorysKey() {
      const account = getCurrentAccount();
      return `menu_prev_historys_${account.id}`;
    },
    /**
     * 激活菜单tab
     * @returns
     */
    menuActiveTabKey() {
      const account = getCurrentAccount();
      return `menu_active_tab_${account.id}`;
    },
  },
  actions: {
    /**
     * 获得新的打开菜单的信息，防止对象引用错误
     * @returns
     */
    getCloneOpenMenus() {
      return this.openMenus.slice(0);
    },
    /**
     * 左侧菜单
     * @param {*} code
     * @returns
     */
    getSiderMenus(code = 'ROOT') {
      return this.getMenuById(code)?.children ?? [];
    },
    /**
     * 通过顶部菜单，获取左侧菜单
     * @param {*} id
     * @returns
     */
    getSiderMenusByTopMenu(id) {
      const topMenu = this.getMenuById(id);
      let siderMenus = [];
      if (topMenu) {
        // 关联一个菜单模块时，左侧菜单只显示菜单模块下级的内容（不显示菜单模块自身）
        if (topMenu.relations.length === 1) {
          siderMenus = this.getSiderMenus(topMenu.relations[0].id);
        } else {
          // 关联了多个菜单模块时，左侧菜单显示  菜单模块（自身）以及下级菜单内容。
          siderMenus = topMenu.relations.map((item) => this.getMenuById(item.id));
        }
      }
      return siderMenus;
    },
    /**
     * 顶部菜单
     * @returns
     */
    getTopMenus() {
      return Array.from(this.topMenus.values()).filter((item) => item.isModel);
    },
    /**
     * 通过左侧菜单获得顶部菜单
     * @param {*} id 左侧菜单ID
     * @returns TopMenu
     */
    getTopMenusBySiderMenu(id) {
      const menu = this.getMenuById(id);
      return menu?.topMenus;
    },
    /**
     * 通过路由获得菜单数据
     * @param {*} route
     */
    getMenuByRoute(route) {
      const menu = this.getMenuById(route.params.menu);
      // 根据code获得id，这种情况，再重新获取菜单数据
      if (isString(menu)) {
        return this.getMenuById(menu);
      }
      return menu;
    },
    /**
     * 根据ID获得菜单数据
     * @param {*} id 菜单ID
     * @returns
     */
    getMenuById(id) {
      return this.siderMenus.get(id) || this.topMenus.get(id);
    },
    /**
     * 解析菜单数据
     * @param {*} data 菜单元数据
     * @param {*} type 菜单类型：sider,top,star,history
     */
    parseMenus(data, type = 'sider') {
      switch (type) {
        case 'sider':
          data?.forEach?.((item) => {
            const menu = new SiderMenu(item);
            this.siderMenus.set(menu.id, menu);
            if (menu.type !== 'MENU' && menu.id !== 'ROOT') {
              this.searchMenus.push(pick(menu, ['id', 'text', 'icon']));
            }
            if (menu.code && !this.siderMenus.has(menu.code)) {
              this.siderMenus.set(menu.code, menu.id);
            }
            // 绑定父节点
            const parent = this.getMenuById(menu.parent);
            parent?.appendChild(menu);
            // 解析子节点
            this.parseMenus(item.children);
          });
          break;
        case 'top':
          data?.forEach?.((item) => {
            const topMenu = new TopMenu(item);
            this.topMenus.set(topMenu.id, topMenu);
            if (topMenu.code && !this.topMenus.has(topMenu.code)) {
              this.topMenus.set(topMenu.code, topMenu.id);
            }
            // 绑定父节点
            topMenu.relations?.forEach(({ id, text }) => {
              const menu = this.getMenuById(id);
              if (menu) {
                let children = [menu];
                while (children.length) {
                  const tempChildren = [];
                  children.forEach((siderMenu) => {
                    siderMenu.topMenus.push(topMenu);
                    tempChildren.push(...(siderMenu.children ?? []));
                  });
                  children = tempChildren;
                }
              } else {
                console.log(`顶部菜单绑定模块未找到：${text}【${id}】`);
              }
            });
          });
          break;
        case 'star':
          this.starMenus = [];
          data?.forEach?.((item) => {
            const menu = this.getMenuById(item.KJMENU_CDID);
            menu && this.starMenus.push(item.KJMENU_CDID);
          });
          break;
        case 'history':
          this.historyMenus = [];
          data?.forEach?.((item) => {
            const menu = this.getMenuById(item.JE_CORE_MENU_ID);
            menu && this.historyMenus.push(item.JE_CORE_MENU_ID);
          });

          break;
      }
    },
    /**
     * 初始化结束
     */
    inited() {
      this.init = true;
    },
    /**
     * 设置初始化顶部菜单
     */
    getInitTopMenu() {
      return this.getTopMenus()[0];
    },
    /**
     * 重置选中的菜单
     */
    resetSelectMenu() {
      this.activeSiderMenu = null; // 激活左侧菜单
      this.activeTopMenu = null; // 激活顶部菜单
    },
    /**
     * 添加历史菜单
     * @param {*} menuId
     */
    addPrevHistoryMenu(menuId) {
      if (!this.prevHistoryMenuEnable) return;

      const index = this.prevHistoryMenus.indexOf(menuId);
      if (index > -1) {
        this.prevHistoryMenus.splice(index, 1);
      }
      this.prevHistoryMenus.unshift(menuId);
      localStorage.setItem(this.menuPrevHistorysKey, this.prevHistoryMenus.join(','));
    },
    /**
     * 清空数据
     */
    clearPrevHistoryMenus(ids = []) {
      let menus = [];
      if (ids.length > 0) {
        menus = this.prevHistoryMenus.filter((id) => !ids.includes(id));
      } else {
        // 记录所有打开的菜单
        menus = this.getCloneOpenMenus();
      }
      this.prevHistoryMenus = menus;
      localStorage.setItem(this.menuPrevHistorysKey, menus.join(','));
    },
    /**
     * 恢复上次操作菜单
     */
    recoverPrevHistoryMenus() {
      const menuIdsStr = localStorage.getItem(this.menuPrevHistorysKey);
      if (isEmpty(menuIdsStr, true)) {
        this.prevHistoryMenuEnable = false;
        return Promise.reject();
      } else {
        const menuIds = split(menuIdsStr, ',').filter((id) => this.getMenuById(id));
        this.prevHistoryMenuEnable = true;
        this.prevHistoryMenus = menuIds;
        return Promise.resolve(this.prevHistoryMenus);
      }
    },
    /**
     * 启用记录操作菜单
     * @param {*} enable
     */
    setPrevHistoryMenuEnable(enable = true) {
      this.prevHistoryMenuEnable = enable;
      if (enable) {
        this.prevHistoryMenus = this.getCloneOpenMenus();
        localStorage.setItem(this.menuPrevHistorysKey, this.prevHistoryMenus.join(','));
      } else {
        localStorage.removeItem(this.menuPrevHistorysKey);
      }
    },
    /**
     * 初始化菜单激活类型
     */
    initMenuActiveTab() {
      this.activeSiderTab = localStorage.getItem(this.menuActiveTabKey) || this.activeSiderTab;
    },
    /**
     * 设置菜单激活类型
     * @param {String} tab
     */
    setMenuActiveTab(tab) {
      this.activeSiderTab = tab;
      localStorage.setItem(this.menuActiveTabKey, tab);
    },
    /**
     * 恢复菜单激活类型
     */
    recoverActiveSiderTab() {
      this.setMenuActiveTab('tree');
    },
    /**
     * 注销
     */
    logout() {
      this.init = false;
      // 重置所有数据
      this.siderMenus.clear(); // 左侧菜单
      this.topMenus.clear(); //顶部菜单
      this.starMenus = []; // 收藏菜单
      this.historyMenus = []; // 历史菜单
      this.activeSiderMenu = null; // 激活左侧菜单
      this.activeTopMenu = null; // 激活顶部菜单
      this.activeSiderTab = 'tree'; // 激活左侧菜单面板
      this.openMenus = []; // 打开的菜单
      this.prevHistoryMenuEnable = false;
      this.prevHistoryMenus = [];
    },
  },
});
